package com.example.wenqujingdian.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.wenqujingdian.R;
import com.example.wenqujingdian.adapter.BookModelListAdapter;
import com.example.wenqujingdian.api.ApiConfig;
import com.example.wenqujingdian.bean.BookDetailBean;
import com.example.wenqujingdian.model.BookModelBean;
import com.example.wenqujingdian.utils.ToastUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.vise.xsnow.http.ViseHttp;
import com.vise.xsnow.http.callback.ACallback;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * 展示5个图书模块的类
 */
public class BookModelActivity extends BaseActivity implements BaseQuickAdapter.OnItemClickListener {

    private static final String TAG = BookModelActivity.class.getCanonicalName();
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.video_recycler)
    RecyclerView recycler;
    @BindView(R.id.smart_refresh)
    SmartRefreshLayout smartRefresh;
    private Unbinder bind;

    private BookModelListAdapter mAdapter;
    private List<BookModelBean.DataBean.ListBean> modelList;
    private boolean isRefresh;
    private int currentPage = 1;
    private int classId;
    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book_model);
        bind = ButterKnife.bind(this);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        Intent intent = getIntent();
        title.setText(intent.getStringExtra("title"));
        classId = intent.getIntExtra("classId",-1);
        progressDialog = new ProgressDialog(this);
        initView();
        initData();
    }

    private void initData() {
        progressDialog.setMessage("加载中...");
        progressDialog.show();
        setRefresh();
        modelList = new ArrayList<>();
        getBookModelList(1);
        mAdapter = new BookModelListAdapter(this,null);
        mAdapter.setOnItemClickListener(this);
        recycler.setAdapter(mAdapter);
    }

    private void getBookModelList(int page) {
        ViseHttp.GET(String.format(ApiConfig.MODUL_URL,classId,page))
                .tag(TAG)
                .baseUrl(ApiConfig.ORG_URL)
                .setHttpCache(true)
                //配置读取超时时间，单位秒
                .readTimeOut(60)
                //配置写入超时时间，单位秒
                .writeTimeOut(60)
                //配置连接超时时间，单位秒
                .connectTimeOut(60)
                //配置请求失败重试次数
                .retryCount(3)
                //配置请求失败重试间隔时间，单位毫秒
                .retryDelayMillis(1000)
                .request(new ACallback<BookModelBean>() {
                    @Override
                    public void onSuccess(BookModelBean data) {
                        progressDialog.dismiss();
                        List<BookModelBean.DataBean> data1 = data.getData();
                        if (data1 == null) return;
                        BookModelBean.DataBean dataBean = data1.get(0);
                        if (isRefresh){
                            modelList = dataBean.getList();
                            mAdapter.replaceData(modelList);
                        }else {
                            modelList.addAll(dataBean.getList());
                            mAdapter.addData(dataBean.getList());
                        }
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        progressDialog.dismiss();
                        ToastUtil.show("error:" + errCode + "\terrMsg:" + errMsg );
                    }
                });
    }

    private void setRefresh() {
        smartRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                autoRefresh();
                refreshLayout.finishRefresh(1000);
            }
        });
        smartRefresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                loadMore();
                refreshLayout.finishLoadMore(1000);
            }
        });
    }

    private void loadMore() {
        isRefresh = false;
        currentPage++;
        getBookModelList(currentPage);
    }

    private void autoRefresh() {
        isRefresh = true;
        currentPage = 1;
        getBookModelList(currentPage);
    }

    private void initView() {
        GridLayoutManager manager;
        if (findViewById(R.id.book_model_land) != null) {
            //横屏显示
            manager = new GridLayoutManager(this, 5);
        } else {
            //竖屏显示
            manager = new GridLayoutManager(this, 3);
        }
        recycler.setLayoutManager(manager);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        bind.unbind();
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        BookModelBean.DataBean.ListBean item = (BookModelBean.DataBean.ListBean) adapter.getData().get(position);
        BookDetailBean bookDetailBean = new BookDetailBean();
        Intent intent = new Intent(BookModelActivity.this, BookDetailsActivity.class);
        bookDetailBean.id = String.valueOf(item.getBookId());
        bookDetailBean.news_tit = item.getBookTitle();
        bookDetailBean.author = item.getAuthor();
        bookDetailBean.jianjie = null;
        bookDetailBean.news_source = item.getPublisher();
        bookDetailBean.spic = item.getCover();
        bookDetailBean.url = item.getBookUrl();
        intent.putExtra("bookDetail", bookDetailBean);
        startActivity(intent);

    }
}
